<?php
declare (strict_types=1);

namespace app\command;

use app\common\Common;
use app\model\Applet;
use app\model\PayRecord;
use app\model\User;
use app\model\Videos;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Queue;

class TiktokOrderSync extends Command
{

    protected function configure()
    {
        // 指令配置
        $this->setName('tiktok-order-sync')
            ->setDescription('抖音订单同步');
    }


    /**
     * 命令行的执行。
     * @param Input $input
     * @param Output $output
     */
    protected function execute(Input $input, Output $output)
    {
        Db::table('ly_pay_record')
            ->alias('pr')
            ->where(['pr.source' => 2,'pr.status' => 1])
            ->leftJoin('user u','pr.uid = u.id')
            ->leftjoin('applet b', 'b.id = u.applet_id')
            ->whereIn('b.id',[65,68])
            ->chunk(1000,function ($items){
                foreach ($items as $info){
                    //订单同步抖音
                    if (!empty($info['video_id'])) {
                        $videos_data = Videos::where('id',$info['video_id'])->field('id,name,cover_img')->find();
                    }
                    $userInfo = User::where('id',$info['uid'])->field('open_id,money, expiration_time, first_charge_date, clickid, interpolate_id, activation_time,ip,ua,advertiser_id,applet_id')->find();
                    $douyinorderurl = 'https://developer.toutiao.com/api/apps/order/v2/push';
                    $order_detail = [ //订单数据
                        'order_id' => $info['order_no'],
                        'create_time' => (int)round(microtime(true) * 1000),
                        'status' => '已支付',
                        'amount' => 1,
                        'total_price' => intval(bcmul($info['total_fee'], '100', 2)),
                        'detail_url' => 'pages/index/index',
                        'item_list' => [[
                            'item_code' => (string)$videos_data['id'] ?? '',
                            'img' => $videos_data['cover_img'] ?? '',
                            'title' => $videos_data['name'] ?? '',
                            'sub_title' => $videos_data['name'] ?? '',
                            'amount' => 1,
                            'price' => intval(bcmul($info['total_fee'], '100', 2))
                        ]]
                    ];
                    $post_data = [
                        'access_token' => $this->getAccessToken($info['uid']),
                        'app_name' => 'douyin',
                        'open_id' => $userInfo['open_id'],
                        'order_detail' => json_encode($order_detail),
                        'order_status' => 1,
                        'order_type' => 0,
                        'update_time' => round(microtime(true) * 1000), //订单信息变更时间，13 位毫秒级时间戳
                    ];
                    flog([
                        'message' => '抖音订单同步参数',
                        'post_data' => $post_data,
                    ],'tiktok');
                    $result = Common::curlRequest($douyinorderurl, 'POST', json_encode($post_data), ['Content-Type: application/json']);
                    flog([
                        'message' => '抖音订单同步结果',
                        'result' => $result,
                    ],'tiktok');
                    dump($info['order_no']);
                    // by update huangxiaoshan 2023-07-17
                    if ($info['link_id'] && $userInfo['clickid'] && $info['advertiser_id']) {

                        $info['clickid'] = $userInfo['clickid'];
                        $info['open_id'] = $userInfo['open_id'];
                        $info['applet_id'] = $userInfo['applet_id'];
                        $info['activation_time'] = $userInfo['activation_time'];

                        // 回传队列延时3秒后执行
                        $jobQueueName = 'postBack';
                        Queue::push('app\job\PostBack', $info, $jobQueueName);
                    }
                }
            },'pr.id','DESC');
    }

    /**
     * 获取小程序token
     * @param $uid 用户id
     * return token
     */
    protected function getAccessToken($uid)
    {
        $redis = Cache::store('redis')->handler();

        $appletData = $this->getAppletInfo($uid);

        $token = $redis->get('douyin_token' . $appletData['id']);
        if (!empty($token)) {
            return $token;
        }
        $token_url = 'https://developer.toutiao.com/api/apps/v2/token';
        //获取抖音token
        $arr = [
            'appid' => $appletData['app_id'],
            'secret' => $appletData['app_secret'],
            'grant_type' => 'client_credential',
        ];
        $data = Common::curlRequest($token_url, 'POST', json_encode($arr));
        $data = json_decode($data, true); //获取token
        if ($data['err_no'] == 0) {
            $token = $data['data']['access_token'];
            $redis->set('douyin_token' . $appletData['id'], $token, $data['data']['expires_in']);
            return $token;
        } else {
            return 0;
        }
    }

    /**
     * 获取小程序配置信息
     * @param $uid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function getAppletInfo($uid): array
    {
        $userInfo = User::where('id',$uid)->field('applet_id ,open_id')->find();

        return Applet::where('id',$userInfo->applet_id)->field('app_id, app_secret,template_id,id')->find()->toArray();
    }
}
